﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using StockFinder.Model;
using StockFinder.Model.Enumerations;
using StockFinder.Network;
using StockFinder.StockLists.SymbolListEnumerators;

namespace StockFinder.StockLists.Exchanges
{
    public class NasdaqOnlineAllNasdaqYahooFinanceOnlinePricesStockList : YahooFinanceOnlinePriceLoaderSymbolListEnumerator
    {
        protected override List<Symbol> GetSymbols()
        {
            const string URL = "http://www.nasdaq.com/screening/companies-by-name.aspx?exchange=NASDAQ&render=download";

            var webClient = new ProxiedWebClient();
            var pageSource = webClient.DownloadString(URL);

            if (string.IsNullOrEmpty(pageSource))
            {
                throw new Exception(string.Format("{0} returned unexpected empty or null string", URL));
            }

            var lines = pageSource.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).Skip(1);

            return lines.Select(line => line.Split(new[] { ',' })).Select(cells => new Symbol { Name = cells[0].Replace("\"", string.Empty).Trim(), Exchange = Exchange.NASDAQ }).ToList();
        }
    }
}
